import 'package:flutter/material.dart';
import 'package:flutter_common_fragement/common/config/index.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

import '../view_model/base_view_model.dart';
import '../view_model/view_state.dart';

class ProviderWidget<T extends BaseViewModel> extends StatefulWidget {
  final T viewModel;
  final ValueWidgetBuilder<T> builder;
  final Widget? child;
  final Function(T)? onModelReady;

  const ProviderWidget(
      {super.key,
      required this.viewModel,
      required this.builder,
      this.child,
      this.onModelReady});

  @override
  State<ProviderWidget<T>> createState() => _ProviderWidgetState<T>();
}

class _ProviderWidgetState<T extends BaseViewModel>
    extends State<ProviderWidget<T>> {
  late T model;

  @override
  void initState() {
    super.initState();
    model = widget.viewModel;

    /// 这里调用initData 可以防止updateWidget的时候viewModel实例化的时候多次执行构造函数中的initData
    model.initData();
    model.viewModelInit();
    widget.onModelReady?.call(model);
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      model.setContext(context);
      model.viewModelInitForContext(context);
    });
  }

  @override
  void reassemble() {
    super.reassemble();
    model.reassemble();
  }

  @override
  void dispose() {
    super.dispose();
    model.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<T>(
      create: (BuildContext context) => model,
      child: Consumer<T>(
        builder: widget.builder,
        child: widget.child,
      ),
    );
  }
}

// class ProviderWidget2<A extends BaseViewModel, B extends BaseViewModel>
//     extends StatefulWidget {
//   final A model1;
//   final B model2;
//   final Widget Function(BuildContext context, A model1, B model2, Widget? child)
//       builder;
//   final Widget? child;
//   final Function(A, B)? onModelReady;
//
//   const ProviderWidget2({
//     super.key,
//     required this.model1,
//     required this.model2,
//     required this.builder,
//     this.child,
//     this.onModelReady,
//   });
//
//   @override
//   _ProviderWidgetState2<A, B> createState() => _ProviderWidgetState2<A, B>();
// }
//
// class _ProviderWidgetState2<A extends BaseViewModel, B extends BaseViewModel>
//     extends State<ProviderWidget2<A, B>> {
//   late A model1;
//   late B model2;
//
//   @override
//   void initState() {
//     super.initState();
//     model1 = widget.model1;
//     model2 = widget.model2;
//     widget.onModelReady?.call(model1, model2);
//   }
//
//   @override
//   void dispose() {
//     super.dispose();
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     return MultiProvider(
//         providers: [
//           ChangeNotifierProvider<A>(create: (BuildContext context) => model1),
//           ChangeNotifierProvider<B>(create: (BuildContext context) => model2)
//         ],
//         child: Consumer2<A, B>(
//           builder: widget.builder,
//           child: widget.child,
//         ));
//   }
// }

class ConsumerWidget<T extends BaseViewModel> extends StatelessWidget {
  // final T viewModel; // 这个viewModel 下面没有用到 可以拿出来也可以注释掉
  final Widget Function(BuildContext context, T vm, Widget? child) builder;
  final bool isMock;
  final Widget? initWidget;
  final Widget? progressWidget;
  final Widget? emptyWidget;
  final Widget? errorWidget;
  final Widget? noNetWidget;
  final Widget? httpErrorWidget;
  final VoidCallback? reloadCallback;

  const ConsumerWidget({
    super.key,
    // required this.viewModel,
    required this.builder,
    this.isMock = false,
    this.initWidget,
    this.progressWidget,
    this.emptyWidget,
    this.errorWidget,
    this.noNetWidget,
    this.httpErrorWidget,
    this.reloadCallback,
  });

  @override
  Widget build(BuildContext context) {
    return Consumer<T>(
      builder: (context, vm, child) {
        /// 成功 这个判断，放到这里 主要是为了适配isMock 不然直接走下面的init return了
        if (vm.viewState == ViewState.success || isMock) {
          return builder.call(context, vm, child);
        }

        /// 初始化
        if (vm.viewState == ViewState.init) {
          return initWidget ?? Container();
        }

        /// 请求中
        if (vm.viewState == ViewState.progress) {
          return progressWidget ?? Container();
        }

        /// empty 只对listview gridview生效
        if (vm.viewState == ViewState.empty) {
          return emptyWidget ?? Container();
        }

        /// 一般对应请求500显示  只在SingleViewModel显示 ListViewModel暂时不显示
        if (vm.viewState == ViewState.responseError) {
          return Center(
            child: errorWidget ??
                Center(
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 15.w),
                    child: httpErrorWidget ??
                        Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            SizedBox(
                              width: 185.h,
                              height: 185.h,
                              child: Image.asset(
                                Constant.noNetImage,
                                fit: BoxFit.cover,
                              ),
                            ),
                            SizedBox(
                              height: 30.h,
                            ),
                            Text(
                              '系统出错，请稍后再试',
                              style: TextStyle(
                                  fontSize: 16.sp,
                                  color: const Color(0xff9B9DA3)),
                              textAlign: TextAlign.center,
                            ),
                            SizedBox(
                              height: 30.h,
                            ),
                            GestureDetector(
                              onTap: () {
                                vm.setInit();
                                if (reloadCallback == null) {
                                  vm.initData();
                                } else {
                                  reloadCallback?.call();
                                }
                              },
                              child: Container(
                                width: 170.w,
                                height: 40.h,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(24.r),
                                  border: Border.all(
                                      color: Theme.of(context).primaryColor,
                                      width: 1.h),
                                ),
                                alignment: Alignment.center,
                                child: Text(
                                  '重新加载',
                                  style: TextStyle(
                                      fontSize: 16.sp,
                                      color: Theme.of(context).primaryColor,
                                      fontWeight: FontWeight.w500),
                                ),
                              ),
                            ),
                          ],
                        ),
                  ),
                ),
          );
        }

        /// 无网络状态
        if (vm.viewState == ViewState.noNet) {
          return Center(
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 15.w),
              child: httpErrorWidget ??
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      SizedBox(
                        width: 185.h,
                        height: 185.h,
                        child: Image.asset(
                          Constant.noNetImage,
                          fit: BoxFit.cover,
                        ),
                      ),
                      SizedBox(
                        height: 30.h,
                      ),
                      Text(
                        '没有网络，请检查网络配置',
                        style: TextStyle(
                            fontSize: 16.sp, color: const Color(0xff9B9DA3)),
                        textAlign: TextAlign.center,
                      ),
                      SizedBox(
                        height: 30.h,
                      ),
                      GestureDetector(
                        onTap: () {
                          vm.setInit();
                          if (reloadCallback == null) {
                            vm.initData();
                          } else {
                            reloadCallback?.call();
                          }
                        },
                        child: Container(
                          width: 170.w,
                          height: 40.h,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(24.r),
                            border: Border.all(
                                color: Theme.of(context).primaryColor,
                                width: 1.h),
                          ),
                          alignment: Alignment.center,
                          child: Text(
                            '重新加载',
                            style: TextStyle(
                                fontSize: 16.sp,
                                color: Theme.of(context).primaryColor,
                                fontWeight: FontWeight.w500),
                          ),
                        ),
                      ),
                    ],
                  ),
            ),
          );
        }

        /// http dio 问题
        if (vm.viewState == ViewState.httpError) {
          vm.clearAllToast();
          return Center(
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 15.w),
              child: httpErrorWidget ??
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      SizedBox(
                        width: 185.h,
                        height: 185.h,
                        child: Image.asset(
                          Constant.noNetImage,
                          fit: BoxFit.cover,
                        ),
                      ),
                      SizedBox(
                        height: 30.h,
                      ),
                      Text(
                        "网络问题，请检查网络配置并稍后重试",
                        style: TextStyle(
                            fontSize: 16.sp, color: const Color(0xff9B9DA3)),
                        textAlign: TextAlign.center,
                      ),
                      SizedBox(
                        height: 30.h,
                      ),
                      GestureDetector(
                        onTap: () {
                          vm.setInit();
                          if (reloadCallback == null) {
                            vm.initData();
                          } else {
                            reloadCallback?.call();
                          }
                        },
                        child: Container(
                          width: 170.w,
                          height: 40.h,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(24.r),
                            border: Border.all(
                                color: Theme.of(context).primaryColor,
                                width: 1.h),
                          ),
                          alignment: Alignment.center,
                          child: Text(
                            '重新加载',
                            style: TextStyle(
                                fontSize: 16.sp,
                                color: Theme.of(context).primaryColor,
                                fontWeight: FontWeight.w500),
                          ),
                        ),
                      ),
                    ],
                  ),
            ),
          );
        }

        /// 默认
        return Container();
      },
      // child: child,
    );
  }
}
